import cv2 as cv
import os
import urllib
import urllib.request

recognizer = cv.face.LBPHFaceRecognizer_create()
recognizer.read('./venv/trainer/trainer.yml')
names=[]


def face_detect_demo(img):
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    face_detector = cv.CascadeClassifier(cv.data.haarcascades+'haarcascade_frontalface_alt2.xml')
    face = face_detector.detectMultiScale(gray)
    for x,y,w,h in face:
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
        cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
        ids,confidence = center=recognizer.predict(gray[y:y+h,x:x+w])
        if confidence > 80:
            cv.putText(img,'unknow',(x + 10,y - 10),cv.FONT_HERSHEY_SIMPLEX,0.75,(0,255,0),1)
        else:
            cv.putText(img, str(names[ids-1]) , (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
    cv.imshow('按空格退出',img)

def name():
    path = './venv/jm/'
    #names = []
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
    for imagePath in imagePaths:
       name = str(os.path.split(imagePath)[1].split('.',2)[1])
       names.append(name)

cap = cv.VideoCapture(0)
name()
while True:
    flag,frame = cap.read()
    if not flag:
        break
    face_detect_demo(frame)
    if ord(' ') == cv.waitKey(10):
        break
cap.release()
cv.destroyAllWindows()